<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css">
    <script src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>
</head>

<body>
<div style="padding-top: 20px;">
    <!--搜索开始-->
    <form class="layui-form layui-form-pane" style="padding-left: 50px">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">图书名称:</label>
                <div class="layui-input-inline">
                    <input name="bookname" type="text" class="layui-input" autocomplete="off" placeholder="员工名称"/>
                </div>
            </div>
            <div class="layui-inline">
                <button lay-filter="searchDemo" lay-submit="" class="layui-btn">搜索</button>

            </div>
        </div>
    </form>
</div>
</div>
<!--搜索结束-->

<!-- 表格 -->
<table class="layui-hide" id="test" lay-filter="test"></table>
<!-- 表格的上面部分 -->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">新增</button>
        <button class="layui-btn layui-btn-sm" lay-event="dels">批量删除</button>
    </div>
    <!-- 表格中的按钮部分 -->
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-sm" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除</a>
</script>
<!--新增的弹出框开始-->
<script type="text/html" id="addDemo">
    <form class="layui-form layui-form-pane">
        <div class="layui-form-item" style="padding-left: 50px;padding-top: 30px">
            <label class="layui-form-label">图书名称</label>
            <div class="layui-input-inline">
                <input type="text" id="names" lay-verify="required" name="bookname" autocomplete="off"
                       class="layui-input">
            </div>
        </div>


        <div class="layui-form-item" style="padding-left: 50px;padding-top: 10px">
            <label class="layui-form-label">创建时间</label>
            <div class="layui-input-inline">
                <input type="text" id="elem" lay-verify="required" name="createdate" autocomplete="off"
                       class="layui-input">
            </div>
        </div>

        <div class="layui-form-item" style="padding-left: 50px;padding-top: 10px">
            <label class="layui-form-label">出版社名称</label>
            <div class="layui-input-inline">
                <select name="pushlishid" lay-filter="aihao" id='selectss'>
                    <option value=""></option>
                </select>
            </div>
        </div>
        <div class="layui-form-item" style="padding-left: 50px;padding-top: 10px">
            <div class="layui-upload">
                <button type="button" class="layui-btn" id="test1">上传图片</button>

                <img class="layui-upload-img" id="demo1" style="width: 50px;height: 50px">
                <p id="demoText" style="width: 50px;height: 50px"></p>

            </div>
        </div>
        <input type="hidden" class="layui-input" lay-submit="" lay-filter="addSumbits" id="addSumbit"/>
    </form>
</script>
<!--新增的弹出框结束-->
<!--编辑的弹出框开始-->
<script type="text/html" id="editDemo">
    <form class="layui-form layui-form-pane" lay-filter="formDemos">
        <div class="layui-form-item" style="padding-left: 50px;padding-top: 30px">
            <label class="layui-form-label">图书名称</label>
            <div class="layui-input-inline">
                <input type="text" id="name" lay-verify="required" name="bookname" autocomplete="off"
                       class="layui-input">


            </div>

        </div>

        <div class="layui-form-item" style="padding-left: 50px;padding-top: 10px">
            <label class="layui-form-label">修改时间</label>
            <div class="layui-input-inline">
                <input type="text" id="elems" lay-verify="required" name="createdate" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="padding-left: 50px;padding-top: 10px">
            <label class="layui-form-label">出版社名称</label>
            <div class="layui-input-inline">
                <select name="pushlishid" lay-filter="aihao" id='selects'>
                    <option value=""></option>
                </select>
            </div>
        </div>
        <div class="layui-form-item" style="padding-left: 50px;padding-top: 10px">
            <div class="layui-upload">

                <button type="button" class="layui-btn" id="test1s">上传图片</button>
                <img class="layui-upload-img" id="demo1s" style="width: 50px;height: 50px">
                <p id="demoTexts" style="width: 50px;height: 50px"></p>
            </div>
        </div>
        <input type="hidden" class="layui-input" lay-submit lay-filter="submitFilter" id="editSumbit"/>
    </form>
</script>
<!--编辑的弹出框结束-->
<script>
    layui.use(['table', 'jquery', 'form', 'upload', 'laydate'], function () {

        var table = layui.table;
        var $ = layui.jquery,
            form = layui.form,
            upload = layui.upload;
        var laydate = layui.laydate;
        // 请求地址前缀
        var pathPrefix = 'http://localhost:8080';

        // 封装ajax 请求
        function getUrl(url, data, method) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: url,
                    data: data,
                    method: method,
                    success: function (result) {
                        resolve(result);
                    },
                    error: function (error) {
                        reject(error);
                    }
                })
            })
        };

        var tab = table.render({
            elem: '#test'
            , url: '/demo/selectAll'
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , title: '图书信息表'
            , cols: [
                [
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'id', title: '编号'}
                    , {field: 'bookname', title: '图书名称'}
                    , {field: 'createdate', title: '创建时间'}
                    , {
                    field: 'pic', title: '图片', templet: function (d) {
                        // 显示图片
                        if (d.pic != null) {
                            return '<img src="/demo' + d.pic + ' " alt="图片详情">'
                        }
                        return d.pic;
                    }
                }
                    , {field: 'pulishes', title: '出版社', templet: '<div>{{d.pulishes.pubname}}</div>'}
                    , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
                ]
            ]
            , page: true

        });
        //头工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            console.log(obj);
            switch (obj.event) {
                case 'add':
                    layer.open({
                        type: 1,
                        title: '新增'
                        , content: $("#addDemo").html(),
                        skin: 'layui-layer-molv',
                        area: ['450px', '400px'],
                        btn: ['新增'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            $("#addSumbit").click();

                        }, success: function (index) {
                            //刷新select
                            form.render();
                            // 时间控件
                            laydate.render({
                                elem: '#elem' //或 elem: document.getElementById('test')、elem: lay('#test') 等
                                , type: 'datetime'
                            })
                            // 查询出出版社的信息
                            getUrl('/demo/pub/selectAll').then((result) => {
                                // 获取所有的dept数据
                                let deptData = result.data;
                                // 进行编辑然后进行拼接
                                $.each(deptData, (index, item) => {
                                    let str = ($("<option value='" + item.pubid + "'>" + item.pubname + "</option>"));
                                    str.appendTo($("#selectss"));
                                })
                                form.render();
                            })
                            //普通图片上传
                            var uploadInst = upload.render({
                                elem: '#test1'
                                , url: '/demo/upload' //改成您自己的上传接口
                                // ,auto:false,
                                // bindAction:'#addSumbit'
                                , before: function (obj) {
                                    //预读本地文件示例，不支持ie8
                                    obj.preview(function (index, file, result) {
                                        $('#demo1').attr('src', result); //图片链接（base64）
                                    });
                                }
                                , done: function (res) {
                                    // 上传成功
                                    // console.log(res);
                                    //layer.closeAll();
                                }
                                , error: function () {
                                    //演示失败状态，并实现重传
                                    var demoText = $('#demoText');
                                    demoText.html('<span style="color: #ff5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                                    demoText.find('.demo-reload').on('click', function () {
                                        uploadInst.upload();
                                    });
                                }
                            });
                            //提交按钮
                            form.on('submit(addSumbits)', function (res) {
                                // 进行提交
                                getUrl("/demo/insertBook", res.field, 'POST').then((result) => {
                                 if (result.code==0){
                                     layer.msg(result.message);
                                     tab.reload();
                                     layer.closeAll();
                                 } else {
                                     layer.msg(result.message);
                                 }
                                })
                                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                            });
                        }
                    });
                    break;
                case 'dels':
                    //对象数组
                    var data = checkStatus.data;
                    var idss = "";
                    if (data.length <= 0) {
                        layer.msg("请最少选中一个");
                        return false;
                    } else {
                        $.each(data, function (index, item) {
                            // 批量删除
                            idss += item.id + ",";
                        })
                         console.log(idss);
                        getUrl("/demo/deleteAll", {_method:'DELETE',ids: idss}, 'POST').then((result) => {

                            if (result.code==0){
                                layer.msg(result.message);
                                tab.reload();
                            } else {
                                layer.msg(result.message);
                            }


                        })
                    }
                    break;

            }
            ;
        });

        //监听行工具事件
        table.on('tool(test)', function (obj) {
            // 当前行的数据
            var data = obj.data;
            // 打印表格数据
            //console.log(data);
            // 删除完成
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    // 进行后端操作
                    getUrl('/demo/delete/' ,{_method: 'DELETE',id:data.id} , 'POST').then((result) => {

                        if (result.code == 0) {
                            tab.reload();
                            layer.msg(result.message);
                            layer.closeAll();
                        } else {
                            layer.msg(result.message);
                        }

                    })


                });

            }
            // 开始编辑
            else if (obj.event === 'edit') {
                layer.open({
                    type: 1,
                    title: '编辑'
                    , content: $("#editDemo").html(),
                    skin: 'layui-layer-molv',
                    area: ['450px', '400px'],
                    btn: ['确定修改'],
                    btnAlign: 'c',
                    yes: function (index, layero) {
                        $("#editSumbit").click();
                    },
                    success: function (layero, index) {
                        // 局部渲染 下拉框
                        form.render();
                        // 时间控件
                        laydate.render({
                            elem: '#elems' //或 elem: document.getElementById('test')、elem: lay('#test') 等
                            , type: 'datetime'
                        })
                        // 编辑信息
                        // 当弹出框出来时  可以将出版社的列表查询出来放到弹出框的表单中
                        // 查询出出版社的信息
                        getUrl('/demo/pub/selectAll').then((result) => {
                            // 获取所有的published数据
                            var deptData = result.data;
                            // 进行编辑然后进行拼接
                            $.each(deptData, (index, item) => {
                                let str = ($("<option value='" + item.pubid + "'>" + item.pubname + "</option>"));
                                str.appendTo($("#selects"));
                            })
                            form.render();
                        })
                        // 下拉框选中
                        getUrl("/demo/select/" + data.id).then((result) => {
                            let deptId = result.data.pushlishid;
                            console.log(deptId);
                            //编辑页面时，对下拉框数据回显
                            $("#selects").each(function () {
                                // this代表的是<option></option>，对option再进行遍历
                                $(this).children("option").each(function () {
                                    // 判断需要对那个选项进行回显
                                    if (this.value == deptId) {
                                        // 进行回显
                                        $(this).attr("selected", "selected");
                                    }
                                });
                                form.render();
                            })
                        })
                        // 回显完成
                        form.val('formDemos', data)

                        //普通图片上传
                        var uploadInst = upload.render({
                            elem: '#test1s'
                            , url: '/demo/upload' //改成您自己的上传接口
                            , before: function (obj) {
                                //预读本地文件示例，不支持ie8
                                obj.preview(function (index, file, result) {
                                    $('#demo1s').attr('src', result); //图片链接（base64）
                                });
                            }
                        });

                        // 进行编辑的提交
                        // 监听提交
                        form.on('submit(submitFilter)', function (datass) {
                            let datas = {};
                            datass.field.id = data.id
                            datas = datass.field;
                            console.log(datas);
                            getUrl("/demo/update", datas, 'POST').then((result) => {
                                if (result.code == 0){
                                    tab.reload()
                                    layer.msg(result.message);
                                    layer.closeAll();
                                } else {
                                    layer.msg(result.message);
                                }

                            })


                            return false;
                        });

                    }
                })
            }
        });

        //监听提交事件  搜索按钮
        form.on('submit(searchDemo)', function (data) {
            console.log(data.field);
            tab.reload({
                url: "/demo/selectAll",
                where: {
                    "bookname": data.field.bookname,
                },
                method: 'get'
            });
            return false;
        })

    });
</script>

</body>

</html>